// Toast提示工具类
import { createApp } from 'vue'
import Toast from '@/components/Toast.vue'

// Toast实例容器（延迟初始化）
let toastContainer = null

// 当前Toast实例列表（存储 { app, el } 对象）
const toastInstances = []

// 初始化容器
const initContainer = () => {
  if (!toastContainer) {
    toastContainer = document.createElement('div')
    toastContainer.id = 'toast-container'
    document.body.appendChild(toastContainer)
  }
}

// 创建Toast实例
const createToast = (message, type = 'success', options = {}) => {
  initContainer()
  
  return new Promise((resolve) => {
    const toastEl = document.createElement('div')
    toastContainer.appendChild(toastEl)
    
    const toastApp = createApp(Toast, {
      message,
      type,
      duration: options.duration ?? 3000,
      showTimestamp: options.showTimestamp !== false,
      onClose: () => {
        // 从列表中移除
        const index = toastInstances.findIndex(item => item.app === toastApp)
        if (index > -1) {
          toastInstances.splice(index, 1)
        }
        
        // 卸载并移除DOM
        toastApp.unmount()
        if (toastEl.parentNode) {
          toastEl.parentNode.removeChild(toastEl)
        }
        
        resolve()
      }
    })
    
    toastApp.mount(toastEl)
    
    // 保存实例
    toastInstances.push({ app: toastApp, el: toastEl })
    
    // 如果Toast数量过多，移除最旧的
    if (toastInstances.length > 5) {
      const oldest = toastInstances.shift()
      oldest.app.unmount()
      if (oldest.el.parentNode) {
        oldest.el.parentNode.removeChild(oldest.el)
      }
    }
  })
}

// 成功提示
export const toastSuccess = (message, options = {}) => {
  return createToast(message, 'success', options)
}

// 错误提示
export const toastError = (message, options = {}) => {
  return createToast(message, 'error', options)
}

// 警告提示
export const toastWarning = (message, options = {}) => {
  return createToast(message, 'warning', options)
}

// 信息提示
export const toastInfo = (message, options = {}) => {
  return createToast(message, 'info', options)
}

// 通用showToast函数
export const showToast = (message, type = 'success', options = {}) => {
  return createToast(message, type, options)
}

// 默认导出（成功类型）
export default {
  success: toastSuccess,
  error: toastError,
  warning: toastWarning,
  info: toastInfo,
  show: showToast
}

